<?php
/**
 * 创建卡券
 */
require_once ('common.php');
error_reporting(false); //禁止错误信息输出

//创建卡券地址
$create_coupon_url = 'https://api.weixin.qq.com/card/create?access_token=';

//1.获取access_token
$access_token = get_access_token();
//2.上传logo获取logo地址
$logo_url = 'http://mmbiz.qpic.cn/mmbiz_jpg/ZaUibzoXdtrBxK5tbTicwEvbebXibAKabcCAia1VibRdotGTZIQwCw6ribA6cw3MItBIly7A4AEfG6Vqlibw1J8V9ibZpA/0';
//3. 创建卡券接口
$data = $_POST; //提交的数据
if(empty($data)){
    echo_Json(-1, '数据不能为空');
}
$card_type = $data['card_type']; //卡券类型 GROUPON 、CASH 、DISCOUNT 、GIFT 、GENERAL_COUPON 
$card_typeArr = array('GROUPON', 'CASH', 'DISCOUNT', 'GIFT', 'GENERAL_COUPON');
if(!in_array($card_type, $card_typeArr)){
    echo_Json(-1, '不合法的卡券类型');
}
/**
 * 卡券基础信息 
 */
//卡券使用期限，有效期
if($data['date_type'] == 'DATE_TYPE_FIX_TERM'){//自领取多长时间内可使用
    $data_info = array(
        'type' => 'DATE_TYPE_FIX_TERM',
        'fixed_term'       => $data['fixed_term'],      //领取后多少天内有效
        'fixed_begin_term' => $data['fixed_begin_term'] ? $data['fixed_begin_term'] : 0, //自领取后多少天开始生效，当天生效填写0
        'end_timestamp'    => $data['end_timestamp']    //卡券过期时间，可以不填
    );
}elseif($data['date_type'] == 'DATE_TYPE_FIX_TIME_RANGE'){ //固定日期区间使用
    $data_info = array(
        'type' => 'DATE_TYPE_FIX_TIME_RANGE',
        'begin_timestamp' => $data['begin_timestamp'],    //卡券起用时间，必填
        'end_timestamp' => $data['end_timestamp']       //卡券过期时间，非必填
    );
}else{
    echo_Json(-1, '不合法的时间类型');
}
$location_id_list = $data['location_id_list'];
if($location_id_list){
    $location_id_listArr = explode(',', $location_id_list);
}
/*--------------------------------卡券基本信息数组--------------------------------------*/
$base_info     = array(
    /*------------必填字段 start-----------*/
    'logo_url'   => $data['logo_url'],   //卡券的商户logo，建议像素为300*300
    'code_type'  => $data['code_type'],  //卡券码型
    'brand_name' => $data['brand_name'], //商户名称，最多12个汉字
    'title'      => $data['title'],      //卡券名称，最多9个汉字 例如：双人套餐100元兑换券
    'color'      => $data['color'],      //卡券颜色，查看文档填写，不能自定义
    'notice'     => $data['notice'],     //卡券使用提醒，最多16个汉字
    'description'=> $data['description'],//卡券使用说明，最多1024个汉字
    'sku'        => array(
        'quantity' => $data['quantity']  //卡券库存的数量，最多为1亿
    ),
    'date_info'  => $data_info,          //卡券的使用日期，有效期的信息
    /*------------必填字段  end-----------*/

    /*------------非必填字段 start-----------*/
    'use_custom_code'       => $data['use_custom_code'] === true ? true : false,  //是否自定义code，默认false
    'get_custom_code_mode'  => $data['get_custom_code_mode '] === 'GET_CUSTOM_CODE_MODE_DEPOSIT' ? 'GET_CUSTOM_CODE_MODE_DEPOSIT' : '',   //表示该卡券为预存code模式卡券,先导入自定义code，quantity字段须为0,须导入code 后再增加库存
    'bind_openid'           => $data['bind_openid'] === true ? true : false, //是否指定用户领取，true指定用户，默认false
    'service_phone'         => $data['service_phone'] ? $data['service_phone'] : '',   //客服电话
    'location_id_list'      => $location_id_listArr ? $location_id_listArr : '', //数组格式，门店位置poiid,线下门店必填
    'use_all_locations'     => $data['use_all_locations'] === false ? false : true, //是否支持全部门店
    'center_title'          => $data['center_title'] ? $data['center_title'] : '',  //卡券顶部居中的按钮文字信息
    'center_sub_title'      => $data['center_sub_title'] ? $data['center_sub_title'] : '', //显示在入口下方的提示语 
    'center_url'            => $data['center_url'] ? $data['center_url'] : '', //顶部居中的url 
    'center_app_brand_user_name' => $data['center_app_brand_user_name'] ? $data['center_app_brand_user_name'] : '',//卡券跳转的小程序的user_name
    'center_app_brand_pass' => $data['center_app_brand_pass'] ? $data['center_app_brand_pass'] : '', //卡券跳转的小程序的path
    'custom_url_name'      => $data['custom_url_name'] ? $data['custom_url_name'] : '', //自定义跳转外链的入口名字
    'custom_url'           => $data['custom_url'] ? $data['custom_url'] : '',  //自定义跳转的url
    'custom_url_sub_title' => $data['custom_url_sub_title'] ? $data['custom_url_sub_title'] : '', //显示在入口右侧的提示语
    'custom_app_brand_user_name' => $data['custom_app_brand_user_name'] ? $data['custom_app_brand_user_name'] : '', //卡券跳转的小程序的user_name
    'custom_app_brand_pass'=> $data['custom_app_brand_pass'] ? $data['custom_app_brand_pass'] : '', //卡券跳转的小程序的path
    'promotion_url_name'   => $data['promotion_url_name'] ? $data['promotion_url_name'] : '', //营销场景的自定义入口名称
    'promotion_url'        => $data['promotion_url'] ? $data['promotion_url'] : '', //入口跳转外链的地址链接
    'promotion_url_sub_title' => $data['promotion_url_sub_title'] ? $data['promotion_url_sub_title'] : '', //显示在营销入口右侧的提示语
    'promotion_app_brand_user_name' => $data['promotion_app_brand_user_name'] ? $data['promotion_app_brand_user_name'] : '',//卡券跳转的小程序的user_name
    'promotion_app_brand_pass'      => $data['promotion_app_brand_pass'] ? $data['promotion_app_brand_pass'] : '', //卡券跳转的小程序的path
    'get_limit'            => $data['get_limit'] ? $data['get_limit'] : 50,  //每人可领的券的数量，默认50
    'use_limit'            => $data['use_limit'] ? $data['use_limit'] : 50,  //每人可核销的券的数量，默认50
    'can_share'            => $data['can_share'] === false ? false : true,     //领券页面是否可以分享
    'can_give_friend'      => $data['can_give_friend'] === false ? false : true, //是否可转赠
    /*------------非必填字段 end-----------*/
);
//处理数组,得到新的$base_info
$base_info = array_filter_recursive($base_info);
/*--------------------------------卡券基本信息数组--------------------------------------*/


/*--------------------------------卡券高级信息数组--------------------------------------*/
if($data['image_url'] && $data['text']){
    $image_url = explode(',', $data['image_url']); //多张图片
    $text = explode(',', $data['text']); //多段文字信息
    if(is_array($image_url) && is_array($text) && count($image_url) > 0 && count($image_url) == count($text)){
        foreach($image_url as $k=>$url){
            $text_image_list[$k] = array(
                'image_url' => $url,
                'text'      => $text[$k]
            );
        }
    }
}
$business_serviceArr = $data['business_service'] ? $data['business_service'] : '';
if($business_serviceArr){
    $business_service = explode(',', $business_serviceArr);
}

//使用时间 time_limit
$use_datetype = $data['use_datetype'];
$begin_hour   = $data['begin_hour'];
$begin_minute = $data['begin_minute'];
$end_hour     = $data['end_hour'];
$end_minute   = $data['end_minute'];
if(is_array($use_datetype)){
    foreach($use_datetype as $k=>$type){
        // var_dump($k);
        // var_dump($begin_hour);
        // var_dump($begin_hour[$k]);die;
        $time_limit[$k] = array(
            'type' => $type,
            'begin_hour' => $begin_hour[$k],
            'begin_minute' => $begin_minute[$k],
            'end_hour'     => $end_hour[$k],
            'end_minute'   => $end_minute[$k]
        );
    }
}


$advanced_info = array(
    'use_condition' => array(             //使用门槛（条件）字段
        'accept_category' => $data['accept_category'] ? $data['accept_category'] : '',  //指定可用的商品类目，仅用于代金券类型
        'reject_category' => $data['reject_category'] ? $data['reject_category'] : '',  //指定不可用的商品类目，仅适用于代金券
        'can_use_with_other_discount' => $data['can_use_with_other_discount'] === false ? false : true,  //不可以与其他类型共享门槛
    ),
    'abstract' => array(
        'abstract' => $data['abstract'] ? $data['abstract'] : '',  //封面摘要结构体名称
        'icon_url_list' => $data['icon_url_list'] ? $data['icon_url_list'] : '', //封面图片列表，仅支持填入一 个封面图片链接
    ),
    'text_image_list' => $text_image_list ? $text_image_list : '',//图文列表，显示在详情内页 ，优惠券开发者须至少传入 一组图文列表
    'business_service' => $business_service, //商家服务类型，可多选
    'time_limit' => $time_limit ? $time_limit : null  //使用时间
);
$advanced_info = array_filter_recursive($advanced_info);
/*--------------------------------卡券高级信息数组--------------------------------------*/


//团购券
if($card_type === 'GROUPON'){
    $deal_detail = $data['deal_detail']; //团购详情，文字描述
    $coupon_data = array(
        'card' => array(
            'card_type' => $card_type,
            'groupon'  => array(
                'base_info' => $base_info,
                'advanced_info' => $advanced_info,
                'deal_detail' => $deal_detail
            )
        )
    );
}
//代金券
elseif($card_type === 'CASH'){ 
    $least_cost = $data['least_cost']; //表示起用金额（单位为分）,如果无起用门槛则填0
    $reduce_cost = $data['reduce_cost']; //表示减免金额。（单位为分）
    $coupon_data = array(
        'card' => array(
            'card_type' => $card_type,
            'cash'  => array(
                'base_info' => $base_info,
                'advanced_info' => $advanced_info,
                'least_cost' => $least_cost,
                'reduce_cost'=> $reduce_cost
            )
        )
    );
}
//折扣券
elseif($card_type === 'DISCOUNT'){
    $discount = $data['discount']; //折扣值
    $coupon_data = array(
        'card' => array(
            'card_type' => $card_type,
            'discount'  => array(
                'base_info' => $base_info,
                'advanced_info' => $advanced_info,
                'discount' => $discount
            )
        )
    );
}
//兑换券
elseif($card_type === 'GIFT'){ 
    $gift = $data['gift']; //填写兑换内容的名称
    $coupon_data = array(
        'card' => array(
            'card_type' => $card_type,
            'gift'  => array(
                'base_info' => $base_info,
                'advanced_info' => $advanced_info,
                'gift' => $gift
            )
        )
    );
}
//优惠券
elseif($card_type === 'GENERAL_COUPON'){ 
    $default_detail = $data['default_detail']; //优惠信息
    $coupon_data = array(
        'card' => array(
            'card_type' => $card_type,
            'discount'  => array(
                'base_info' => $base_info,
                'advanced_info' => $advanced_info,
                'default_detail' => $default_detail
            )
        )
    );
}
$card_result = create_coupon($create_coupon_url.$access_token, $coupon_data);
if($card_result['code'] == 0){
    echo_Json(0, '卡券创建成功', $card_result['card_id']);
}else{
    echo_Json($card_result['code'], '卡券创建失败');
}

//创建卡券
function create_coupon($create_coupon_url, $coupon_data){
    $card_Arr = jsonpostJson($create_coupon_url, $coupon_data, true); //post请求
    if($card_Arr['errcode'] != 0){
        $result = array(
            'code' => $card_Arr['errcode']
        );
    }else{
        $result = array(
            'code' => 0,
            'card_id' => $card_Arr['card_id']
        );
    }
    return $result;
}
